package com.xuesaieducation.zshddemo;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.flyco.tablayout.SlidingTabLayout;
import com.gensee.common.ServiceType;
import com.gensee.entity.InitParam;
import com.gensee.entity.PingEntity;
import com.gensee.media.VODPlayer;
import com.gensee.player.OnPlayListener;
import com.gensee.player.Player;
import com.gensee.vod.VodSite;
import com.xuesaieducation.zshddemo.fragments.ChatFragment;
import com.xuesaieducation.zshddemo.fragments.DocFragment;
import com.xuesaieducation.zshddemo.fragments.VideoFragment;
import com.xuesaieducation.zshddemo.fragments.VodFragment;

import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;

public class GenSeePlayActivity extends AppCompatActivity implements
        DocFragment.FullScreenClickListener,
        VideoFragment.VideoFragListener,
        VodFragment.FullScreenClickListener
{
    @BindView(R.id.tab)
    SlidingTabLayout tab;
    @BindView(R.id.pager)
    ViewPager pager;
    @BindView(R.id.video_parent)
    FrameLayout videoParent;
    @BindView(R.id.video_container)
    FrameLayout videoContainer;

    @BindView(R.id.wait)
    ProgressBar wait;

    /**
     * 直播需要的播放器
     */
    private Player mLivePlayer;
    private GenseeOnPlayCallback livePlayCallback;

    /**
     * 回放需要的播放器
     */
    private VODPlayer mVodPlayer;
    private GenseeVodCallback vodCallback;
    private GenseeGSOLCallback vodGsolCallback;

    private VodSite vodSite;

    /**
     * 不是直播就是点播
     */
    private boolean isLive;
    /**
     * 域名
     */
    private String domainName;
    /**
     * 是否提供直播id的方式播放
     */
    private boolean isLiveIdProvided;
    /**
     * 直播id
     */
    private String liveId;
    /**
     * 编号
     */
    private String number;
    private String localVideoPath;
    /**
     * 是否需要登录
     */
    private boolean needLogin;
    private String userName;
    private String userPwd;
    /**
     * 昵称，可以为空，系统自动生成
     */
    private String nickName;
    /**
     * 加入口令
     */
    private String joinPwd;
    /**
     * 服务类型
     */
    private int serviceType;
    public static final int TYPE_TRAINING = 1;
    public static final int TYPE_WEBCAST = 2;

    private int videoParentWidth, videoParentHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_gen_see_play);
        ButterKnife.bind(this);
        videoParent.post(new Runnable()
        {
            @Override
            public void run()
            {
                videoParentWidth = videoParent.getMeasuredWidth();
                videoParentHeight = videoParent.getMeasuredHeight();
            }
        });
        init();
    }

    private void init()
    {
        getIntentData();
        final InitParam p = initParam();
        if (isLive)
        {
            mLivePlayer = new Player();
            videoFrag = new VideoFragment(mLivePlayer);
            videoFrag.setVideoFragListener(this);
            mLivePlayer.join(getApplicationContext(), p, new GenseeOnPlayCallback(this)
            {
                @Override
                public void onJoinSuccess()
                {
                    wait.setVisibility(View.GONE);
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.video_container, videoFrag)
                            .commit();
                    pager.setAdapter(new Ad(getSupportFragmentManager()));
                    tab.setViewPager(pager);
                    videoFrag.onJoin(true);
                }

                @Override
                public void onError(int code, String msg)
                {
                    wait.setVisibility(View.GONE);
                    Toast.makeText(GenSeePlayActivity.this, msg, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onWait(boolean yn)
                {
                    if (yn)
                        wait.setVisibility(View.VISIBLE);
                    else
                        wait.setVisibility(View.GONE);
                }

                @Override
                public void onRetrievePersonCount(int count)
                {
                    if (videoFrag != null)
                    {
                        videoFrag.onPersonCount(count);
                    }
                }

                @Override
                public void onRetrieveMicState(int notify)
                {
                    switch (notify)
                    {
                        case MicNotify.MIC_COLSED:
                            videoFrag.onMicColesed();
                            mLivePlayer.inviteAck(OnPlayListener.INVITE_AUIDO, false, null);
                            break;
                        case MicNotify.MIC_OPENED:
                            videoFrag.onMicOpened(OnPlayListener.INVITE_AUIDO);
                            mLivePlayer.inviteAck(OnPlayListener.INVITE_AUIDO, true, null);
                            break;
                        case MicNotify.MIC_OPEN_FAILED:
                            Toast.makeText(GenSeePlayActivity.this,
                                    "麦克风打开失败，请重试并允许程序打开麦克风", Toast.LENGTH_SHORT).show();
                            mLivePlayer.openMic(GenSeePlayActivity.this, false, null);
                            mLivePlayer.inviteAck(OnPlayListener.INVITE_AUIDO, false, null);
                            break;
                        default:
                            break;
                    }
                }

                @Override
                public void onRetrieveRespond(int type, boolean isOpen)
                {
                    if (isOpen)
                    {
                        videoFrag.onInviteResponse();
                    }
                }

                @Override
                public void OnRetrieveIdc(List<PingEntity> list)
                {
                    if (videoFrag != null)
                    {
                        videoFrag.onIdcList(list);
                    }
                }

                @Override
                public void onRetrieveTitle(String title)
                {
                    if (videoFrag != null)
                    {
                        videoFrag.onTitle(title);
                    }
                }
            });
        }
    }

    private void getIntentData()
    {
        Intent it = getIntent();
        isLive = it.getBooleanExtra("isLive", true);
        domainName = it.getStringExtra("domainName");
        if (TextUtils.isEmpty(domainName))
        {
            domainName = "ujigu.gensee.com";
        }
        isLiveIdProvided = it.getBooleanExtra("isLiveIdProvided", false);
        liveId = it.getStringExtra("liveId");
        number = it.getStringExtra("number");
        needLogin = it.getBooleanExtra("needLogin", false);
        userName = it.getStringExtra("userName");
        userPwd = it.getStringExtra("userPwd");
        nickName = it.getStringExtra("nickName");
        localVideoPath = it.getStringExtra("play_path");
        if (TextUtils.isEmpty(nickName))
        {
            nickName = getRandomName();
        }
        joinPwd = it.getStringExtra("joinPwd");
        serviceType = it.getIntExtra("serviceType", TYPE_TRAINING);
    }

    private InitParam initParam()
    {
        InitParam initParam = new InitParam();
        initParam.setDomain(domainName);
        if (!isLiveIdProvided)
        {
            initParam.setNumber(number);
        } else
        {
            initParam.setLiveId(liveId);
        }
        if (needLogin)
        {
            initParam.setLoginAccount(userName);
            initParam.setLoginPwd(userPwd);
        }
        initParam.setNickName(nickName);
        initParam.setServiceType(serviceType == TYPE_TRAINING ? ServiceType.TRAINING : ServiceType.WEBCAST);
        if (isLive)
        {
            initParam.setJoinPwd(joinPwd);
        } else
        {
            if (!TextUtils.isEmpty(localVideoPath))
            {
                setVodPlayer(null);
            } else
            {
                initParam.setVodPwd(joinPwd);
                vodSite = new VodSite(this);
                vodSite.setVodListener(new GenseeVodCallback(this)
                {

                    @Override
                    public void onSuccess(String vodId)
                    {
                        setVodPlayer(vodId);
                    }

                    @Override
                    public void onFailed()
                    {
                        wait.setVisibility(View.GONE);
                    }
                });
                vodSite.getVodObject(initParam);
                wait.setVisibility(View.VISIBLE);
            }
        }
        return initParam;
    }

    private void setVodPlayer(String vodId)
    {
        mVodPlayer = new VODPlayer();
        vodFrag = new VodFragment();
        vodFrag.setFullScreenClickListener(GenSeePlayActivity.this);
        vodFrag.setPlayer(mVodPlayer, new VodFragment.Callback()
        {
            @Override
            public void isWait(boolean yn)
            {
                if (yn)
                    wait.setVisibility(View.VISIBLE);
                else
                    wait.setVisibility(View.GONE);
            }

            @Override
            public void onStart()
            {
                wait.setVisibility(View.GONE);
            }

            @Override
            public void onError(int code, String msg)
            {
                wait.setVisibility(View.GONE);
                Toast.makeText(GenSeePlayActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });
        Bundle bd = new Bundle();
        if (!TextUtils.isEmpty(vodId))
        {
            bd.putString("play_param", vodId);
        }
        if (!TextUtils.isEmpty(localVideoPath))
        {
            bd.putString("play_path", localVideoPath);
        }

        vodFrag.setArguments(bd);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.video_container, vodFrag)
                .commit();
        pager.setAdapter(new Ad(getSupportFragmentManager()));
        tab.setViewPager(pager);
    }

    private String getRandomName()
    {
        Random rd = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 8; i++)
        {
            sb.append((char) (rd.nextInt(26) + 'a'));
        }
        return sb.toString();
    }

    private VodFragment vodFrag;
    private VideoFragment videoFrag;
    private DocFragment docFrag;
    private ChatFragment chatFrag;

    int witchFullScreen;
    public static final int FULL_LIVE_VIDEO = 1;
    public static final int FULL_REVIEW_VIDEO = 3;
    public static final int FULL_DOC = 2;

    @Override
    public void docClick()
    {
        witchFullScreen = FULL_DOC;
        if (ScreenUtils.isPortrait(this))
        {
            ScreenUtils.setLandscape(this);
        } else
        {
            ScreenUtils.setPortrait(this);
        }
    }

    @Override
    public void onLiveExit()
    {
        GenSeePlayActivity.this.onBackPressed();
    }

    @Override
    public void onLiveFullScreenClick()
    {
        witchFullScreen = FULL_LIVE_VIDEO;
        if (ScreenUtils.isPortrait(GenSeePlayActivity.this))
        {
            ScreenUtils.setLandscape(GenSeePlayActivity.this);
        } else
        {
            ScreenUtils.setPortrait(GenSeePlayActivity.this);
        }
    }

    @Override
    public void vodClick()
    {
        witchFullScreen = FULL_REVIEW_VIDEO;
        if (ScreenUtils.isPortrait(GenSeePlayActivity.this))
        {
            ScreenUtils.setLandscape(GenSeePlayActivity.this);
        } else
        {
            ScreenUtils.setPortrait(GenSeePlayActivity.this);
        }
    }

    class Ad extends FragmentStatePagerAdapter
    {
        Ad(FragmentManager fm)
        {
            super(fm);
        }

        String[] ts = new String[]{"文档", "聊天"};

        @Override
        public CharSequence getPageTitle(int position)
        {
            return ts[position];
        }

        @Override
        public Fragment getItem(int position)
        {
            if (position == 0)
            {
                if (isLive)
                {
                    if (docFrag == null)
                    {
                        docFrag = new DocFragment();
                        docFrag.setLivePlayer(mLivePlayer);
                        docFrag.setFullScreenClickListener(GenSeePlayActivity.this);
                    }
                } else
                {
                    if (docFrag == null)
                    {
                        docFrag = new DocFragment();
                        docFrag.setVodPlayer(mVodPlayer);
                        docFrag.setFullScreenClickListener(GenSeePlayActivity.this);
                    }
                }
                return docFrag;
            } else
            {
                if (chatFrag == null)
                {
                    chatFrag = new ChatFragment(mLivePlayer);
                }
                return chatFrag;
            }
        }

        @Override
        public int getCount()
        {
            return isLive ? 2 : 1;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        if (ScreenUtils.isPortrait(this))
        {
            tab.setVisibility(View.VISIBLE);

            if (witchFullScreen == FULL_LIVE_VIDEO)
            {
                handleVideoOritention();
                videoFrag.handleScreenOritention();
                pager.setVisibility(View.VISIBLE);
                if (docFrag != null)
                    docFrag.resumeDoc();
            } else if (witchFullScreen == FULL_DOC)
            {
                videoParent.setVisibility(View.VISIBLE);
                if (videoFrag != null)
                    videoFrag.setVideoViewVisible(true);
                if (vodFrag != null)
                    vodFrag.setVideoViewVisible(true);
                docFrag.handleScreenOritention();
            } else if (witchFullScreen == FULL_REVIEW_VIDEO)
            {
                handleVideoOritention();
                vodFrag.handleScreenOritention();
                pager.setVisibility(View.VISIBLE);
                if (docFrag != null)
                    docFrag.resumeDoc();
            }
        } else
        {
            tab.setVisibility(View.GONE);

            if (witchFullScreen == FULL_LIVE_VIDEO)
            {
                handleVideoOritention();
                videoFrag.handleScreenOritention();
                pager.setVisibility(View.GONE);
                if (docFrag != null)
                    docFrag.pauseDoc();
            } else if (witchFullScreen == FULL_REVIEW_VIDEO)
            {
                handleVideoOritention();
                vodFrag.handleScreenOritention();
                pager.setVisibility(View.GONE);
                if (docFrag != null)
                    docFrag.pauseDoc();
            } else
            {
                videoParent.setVisibility(View.GONE);
                if (videoFrag != null)
                    videoFrag.setVideoViewVisible(false);
                if (vodFrag != null)
                    vodFrag.setVideoViewVisible(false);
                docFrag.handleScreenOritention();
            }
        }
    }

    private void handleVideoOritention()
    {
        if (ScreenUtils.isPortrait(this))
        {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) videoParent.getLayoutParams();
            p.width = videoParentWidth;
            p.height = videoParentHeight;
            videoParent.setLayoutParams(p);
        } else
        {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) videoParent.getLayoutParams();
            p.width = ScreenUtils.screenWidth(this);
            p.height = ScreenUtils.screenHeight(this);
            videoParent.setLayoutParams(p);
        }
    }

    @Override
    public void onBackPressed()
    {
        if (handleLandScape())
        {
            return;
        } else
        {
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("确认退出？")
                    .setPositiveButton("退出", new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            GenSeePlayActivity.super.onBackPressed();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }

    }

    private boolean handleLandScape()
    {
        if (ScreenUtils.isLandscape(this))
        {
            ScreenUtils.setPortrait(this);
            if (witchFullScreen == FULL_LIVE_VIDEO)
            {
                videoFrag.handleScreenOritention();
            } else if (witchFullScreen == FULL_REVIEW_VIDEO)
            {
                vodFrag.handleScreenOritention();
            } else
            {
                docFrag.handleScreenOritention();
            }
            return true;
        }
        return false;
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        releasePlayer();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
    }

    private void releasePlayer()
    {
        if (null != mLivePlayer)
        {
            mLivePlayer.leave();
            mLivePlayer.release(this);
        }

        if (mVodPlayer != null)
        {
            mVodPlayer.release();
        }
    }

}
